/*
 * @author Maver1ck
 * */

package com.learning.downloader;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.util.ByteArrayBuffer;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

/*
 * here we are going to use an AsyncTask to download the image 
 *      in background while showing the download progress
 * */

public class ImageDownloader extends AsyncTask<Void, Integer, Void> {


	private String url;
	private Context c;




	/*--- constructor ---*/
	public ImageDownloader(String url,Context c) {
	/*--- we need to pass some objects we are going to work with ---*/
		this.url = url;
		this.c = c;

	}
	
	/*--- we need this interface for keeping the reference to our Bitmap from the MainActivity. 
	 *  Otherwise, bmp would be null in our MainActivity*/
	public interface ImageLoaderListener {
		
		void onImageDownloaded(Bitmap bmp);
		
		}

	@Override
	protected void onPreExecute() {

		Toast.makeText(c, "starting download", Toast.LENGTH_SHORT).show();

		super.onPreExecute();
	}

	@Override
	protected Void doInBackground(Void... arg0) {

		downloadVideoFromURL(url);
		return null;
	}



	@Override
	protected void onPostExecute(Void result) {

		
		Toast.makeText(c, "download complete", Toast.LENGTH_SHORT).show();

		super.onPostExecute(result);
	}

	public void downloadVideoFromURL(String link) {

		try {
			String fileName = "/sdcard/baohau.mp4";
			URL url = new URL(link);
			File file = new File(fileName);
			URLConnection ucon = url.openConnection();
			InputStream is = ucon.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(is);
			ByteArrayBuffer baf = new ByteArrayBuffer(1000);
			int current = 0;
			int xaone = 0;
			while ((current = bis.read()) != -1) {
			baf.append((byte) current);
			xaone+=current;
			}
			
			FileOutputStream fos = new FileOutputStream(file);
			fos.write(baf.toByteArray());
			fos.close();
		}
	    catch(Exception e)
	    {
	    }
	}

}
